# coding=utf8
import commands
import time


def calculate_rx_tx():
    """
    计算linux 当前网络
    :return:
    """
    print(u"当前网络信息如下:\n")
    record_before_rx_tx = {}
    while(True):
        info = commands.getoutput("cat /proc/net/dev")
        info_arr = info.split('\n')
        info_arr_len = len(info_arr)
        if info_arr_len <= 2:
            print(u"请检查网卡信息\n")
            return

        for i in range(2, info_arr_len):
            rx_tx = info_arr[i]
            title, rx_tx_info = rx_tx.split(":")
            rx_tx_info = rx_tx_info.split()
            title = title.replace(' ', '')
            rx = int(rx_tx_info[1])
            tx = int(rx_tx_info[9])
            before_rx = record_before_rx_tx.get(title+'_rx')
            before_tx = record_before_rx_tx.get(title+'_tx')
            if not before_rx:
                before_rx = rx
            if not before_tx:
                before_tx = tx
            print('{0}:RX/s {1} kb/s, TX/s {2} kb/s'.format(title, (rx-before_rx)/1024, (tx-before_tx)/1024))
            record_before_rx_tx[title+'_rx'] = rx
            record_before_rx_tx[title+'_tx'] = tx
        print('\n')
        time.sleep(1)


def main():
    calculate_rx_tx()


if __name__ == '__main__':
    main()